package com.example.common.handler;

import com.example.common.domain.Result;
import com.example.common.exception.BaseException;
import com.example.common.exception.BizIllegalException;
import com.example.common.exception.CaptchaException;
import com.example.common.exception.UpdatePasswordException;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BaseException.class)
    public Result error(BaseException ex) {// 会把拦截到的异常传递给方法的形参
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    // 处理校验参数抛出的异常
    @ExceptionHandler
    public Result handleBindException(MethodArgumentNotValidException ex) {
    /*
      ex.getFieldError().getDefaultMessage():获取 @NotNull(message="xxx") 中message的消息
    */
        String message = ex.getFieldError().getDefaultMessage();
        log.error("异常信息：{}",message);
        return Result.error(message);
    }

    @ExceptionHandler
    public Result handleConstraintViolationException(ConstraintViolationException ex) {
        String message = ex.getMessage();
        //register.phone: 手机号不能为null、空字符串和空白串
        // 截取字符串：从冒号后面的内容开始截取，并去除空格
        message = message.substring(message.indexOf(':')+2).trim();
        log.error("异常信息：{}", message);
        return Result.error(message);
    }
    @ExceptionHandler(CaptchaException.class)
    public Result handleCaptchaException(CaptchaException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(UpdatePasswordException.class)
    public Result handleUpdatePasswordException(UpdatePasswordException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(BizIllegalException.class)
    public Result handleBizIllegalException(BizIllegalException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }




}
